import {getUserTempId} from "@/utils/userabout";
import {reqGetCode, reqUserInfo, reqUserLogin, reqUserLogout, reqUserRegister} from "@/api";


const state = {
    userTempId: getUserTempId(),
    code: '',
    token: localStorage.getItem('token_key'),
    userInfo: {}
}
const mutations = {
    SET_CODE(state, code) {
        state.code = code
    },
    SET_TOKEN(state, token) {
        state.token = token
    },
    SET_USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    REMOVE_TOKEN_USERINFO(state) {
        state.token = ''
        state.userInfo={}
    }
}
const actions = {
    //获取验证码
    async getCode({commit}, phone) {
        const result = await reqGetCode(phone)
        if (result.code === 200) {
            commit('SET_CODE', result.data)
            return result.data
        } else {
            return Promise.reject(new Error('failed'))
        }

    },
    //请求注册
    // eslint-disable-next-line no-unused-vars
    async getUserRegister({commit}, userInfo) {
        const result = await reqUserRegister(userInfo)
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    },
    //用户登录
    async getUserLogin({commit}, userInfo) {
        const result = await reqUserLogin(userInfo)
        if (result.code === 200) {
            commit('SET_TOKEN', result.data.token)//这是为了第一次登陆显示做准备
            localStorage.setItem('token_key', result.data.token)//这是为了之后刷新页不会丢失token信息
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },
    //获取用户信息
    async getUserInfo({commit}) {
        const result = await reqUserInfo()
        if (result.code === 200) {
            commit('SET_USERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },

    //清空token信息和用户信息
    getRemoveTokenAndUserInfo({commit}) {
        localStorage.removeItem('token_key'),
            commit('REMOVE_TOKEN_USERINFO')
    },
    //退出登录
    // eslint-disable-next-line no-unused-vars
    async getUserLogout({commit,dispatch}) {
        const result=await reqUserLogout()
        if (result.code === 200) {
            //退出登录成功清楚token和userInfo
            dispatch('getRemoveTokenAndUserInfo')
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    }

}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}
